from request import post_req
from datetime import datetime


def get_tenant_access_token():
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
    headers = {
        "Content-Type": "application/json"
    }
    req_body = {
        "app_id": config.APP_ID,
        "app_secret": config.APP_SECRET
    }
    
    rsp_dict = post_req(url, headers, req_body)
    
    code = rsp_dict.get("code", -1)
    if code != 0:
        print("get tenant_access_token error, code =", code)
        return ""
    
    return rsp_dict.get("tenant_access_token", "")


class CONFIG:
    APP_ID = "cli_a1a1c6df3db8900d"
    APP_SECRET = "fbFQ4tFVjenfvyiMAoeQkfEHD8twVTXF"
    APP_VERIFICATION_TOKEN = "UlXzu1sa9XGbXxcGNY57QgwhlaKYjItZ"
    APP_ADDRESS = "http://paper.fastnlp.top"
    
    def __init__(self):
        self.storage = {}
    
    def tenant_access_token(self, update=False):
        nowTime = datetime.now()
        if update:
            self.storage["data"] = get_tenant_access_token()
            self.storage["time"] = nowTime
        elif "data" not in self.storage or "time" not in self.storage:
            self.storage["data"] = get_tenant_access_token()
            self.storage["time"] = nowTime
        elif (nowTime - self.storage["time"]).seconds >= 1800:
            self.storage["data"] = get_tenant_access_token()
            self.storage["time"] = nowTime
        return self.storage["data"]


config = CONFIG()
